package com.hnqcgczy.sgzTest.dao.impl;

import com.hnqcgczy.sgzTest.dao.GoodDao;
import com.hnqcgczy.sgzTest.db.DB;
import com.hnqcgczy.sgzTest.db.DBUtils;
import com.hnqcgczy.sgzTest.db.MySqlTransaction;
import com.hnqcgczy.sgzTest.pojo.TProduct;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class GoodDaoImpl implements GoodDao {

    private MySqlTransaction tran;

    public GoodDaoImpl(MySqlTransaction tran) {
        this.tran = tran;
    }

    @Override
    public List<TProduct> getAllGood() throws SQLException {
        //1.获得数据库连接  用MySqlTransaction
//        DB db=new DBUtils();
//        MySqlTransaction tran = new MySqlTransaction(db, true);
       Connection conn = tran.getConnByTran();
        //2、发送sql语句
        PreparedStatement ps = conn.prepareStatement("select * from t_product");
        //3、执行sql语句
       // ps.executeUpdate()
        ResultSet rs = ps.executeQuery();
        List<TProduct> product_list=new ArrayList<>();
        while (rs.next()){
            TProduct tProduct=new TProduct();
            //准备存储数据
            tProduct.setTpId(rs.getInt(1));
            tProduct.setTpName(rs.getString(2));
            tProduct.setTpDescription(rs.getString(3));
            tProduct.setTpPrice(rs.getDouble(4));
            tProduct.setTpStock(rs.getInt(5));
            tProduct.setTpcId(rs.getInt(6));
            tProduct.setTpcChildId(rs.getInt(7));
            tProduct.setTpFileName(rs.getString(8));
            //将每个对象放入袋子中
            product_list.add(tProduct);
        }

        //4、释放资源
        if(rs!=null) {
            rs.close();
        }
        if(ps!=null){
            ps.close();
        }

        //5、关闭数据库
        if(conn!=null){
            conn.close();
        }


        return product_list;
    }


    public static void main(String[] args) {
        DB db=new DBUtils();
        MySqlTransaction tran = new MySqlTransaction(db, true);
        GoodDaoImpl goodDao = new GoodDaoImpl(tran);
        try {
            List<TProduct> allGood = goodDao.getAllGood();
            System.out.println(allGood.size());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

    }
}
